package com.misyi.designpattern.factory.factorymethod;

/**
 * 工厂方法模式
 *
 * @author licong
 * @date 2021-09-11 上午11:01
 */
public class FactoryMethodPatternDemo {

    public static void main(String[] args) {
        Product product1 = Product1Factory.getInstance().create();
        product1.execute();
        Product product2 = Product2Factory.getInstance().create();
        product2.execute();
        Product product3 = Product3Factory.getInstance().create();
        product3.execute();
    }


    public interface Product {
        void execute();
    }


    public static class Product1 implements Product {

        @Override
        public void execute() {
            System.out.println("产品 1 的功能逻辑");
        }
    }

    public static class Product2 implements Product {

        @Override
        public void execute() {
            System.out.println("产品 2 的功能逻辑");
        }
    }

    public static class Product3 implements Product {

        @Override
        public void execute() {
            System.out.println("产品 3 的功能逻辑");
        }
    }


    public abstract static class AbstractProductFactory {

        public Product create() {
            commonCreate();
            return specialCreate();
        }

        // 通用逻辑方法
        private void commonCreate() {
            System.out.println("生产产品的通用逻辑");
        }

        protected abstract Product specialCreate();
    }

    public static class Product1Factory extends AbstractProductFactory {
        private static final Product1Factory INSTANCE = new Product1Factory();

        private Product1Factory() {
        }

        public static Product1Factory getInstance() {
            return INSTANCE;
        }

        @Override
        protected Product specialCreate() {
            System.out.println("生产产品 1 的特殊逻辑");
            return new Product1();
        }
    }

    public static class Product2Factory extends AbstractProductFactory {
        private static final Product2Factory INSTANCE = new Product2Factory();

        private Product2Factory() {
        }

        public static Product2Factory getInstance() {
            return INSTANCE;
        }
        @Override
        protected Product specialCreate() {
            System.out.println("生产产品 2 的特殊逻辑");
            return new Product2();
        }
    }

    public static class Product3Factory extends AbstractProductFactory {
        private static final Product3Factory INSTANCE = new Product3Factory();

        private Product3Factory() {
        }

        public static Product3Factory getInstance() {
            return INSTANCE;
        }
        @Override
        protected Product specialCreate() {
            System.out.println("生产产品 3 的特殊逻辑");
            return new Product3();
        }
    }
}
